/**
 * 通用API
 */
import { get, post, put, del } from './index'
import type { ApiResponse, StatisticsData, Notification } from '@/types'

// 系统统计
export const getSystemStatistics = () => {
  return get<ApiResponse<StatisticsData>>('/common/statistics/')
}

export const getDashboardData = () => {
  return get<ApiResponse<any>>('/common/dashboard/')
}

// 文件上传
export const uploadFile = (file: File, type: 'image' | 'document' | 'media' = 'document') => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', type)
  return post<ApiResponse<{ url: string; name: string; size: number }>>(
    '/common/upload/',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )
}

export const deleteFile = (fileUrl: string) => {
  return del('/common/delete-file/', { file_url: fileUrl })
}

// 通知管理
export const getNotifications = (params?: { page?: number; page_size?: number; unread_only?: boolean }) => {
  return get<ApiResponse<{ results: Notification[]; count: number }>>('/common/notifications/', params)
}

export const markNotificationAsRead = (notificationId: string) => {
  return post(`/common/notifications/${notificationId}/read/`)
}

export const markAllNotificationsAsRead = () => {
  return post('/common/notifications/read-all/')
}

export const deleteNotification = (notificationId: string) => {
  return del(`/common/notifications/${notificationId}/`)
}

// 系统配置
export const getSystemSettings = () => {
  return get<ApiResponse<any>>('/common/settings/')
}

export const updateSystemSettings = (data: any) => {
  return put<ApiResponse<any>>('/common/settings/', data)
}

// 搜索
export const globalSearch = (params: {
  q: string
  type?: 'all' | 'questions' | 'exams' | 'papers' | 'users'
  page?: number
  page_size?: number
}) => {
  return get<ApiResponse<any>>('/common/search/', params)
}

// 日志管理
export const getSystemLogs = (params?: {
  page?: number
  page_size?: number
  level?: string
  start_date?: string
  end_date?: string
  user?: number
}) => {
  return get<ApiResponse<any>>('/common/logs/', params)
}

// 数据导出
export const exportData = (data: {
  type: 'questions' | 'exams' | 'grades' | 'users'
  format: 'excel' | 'csv'
  filters?: any
}) => {
  return post('/common/export/', data)
}

// 数据导入
export const importData = (type: string, file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', type)
  return post<ApiResponse<{ imported: number; errors: string[] }>>(
    '/common/import/',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )
}

// 健康检查
export const healthCheck = () => {
  return get<ApiResponse<{ status: string; version: string }>>('/common/health/')
}

// 版本信息
export const getVersionInfo = () => {
  return get<ApiResponse<{ version: string; build: string; features: string[] }>>('/common/version/')
}